package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.dto.ApUserSearch;
import com.heima.search.service.IApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: itheima
 * @create: 2022-04-04 11:46
 */
@Service
public class ApUserSearchServiceImpl implements IApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索记录记录到MongoDB中
     *
     * @param keyword     搜索关键字
     * @param userId      用户ID
     * @param equipmentId 设备ID
     */
    @Override
    @Async("leadnewsExecutor")
    public void saveSearchRecord(String keyword, Integer userId, String equipmentId) {
        //1.判断用户或者设备是否已经搜索过该记录
        //1.1 构建查询条件Query封装查询
        Query query = new Query();
        if (userId != null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        } else {
            query.addCriteria(Criteria.where("equipmentId").is(equipmentId));
        }
        query.addCriteria(Criteria.where("keyword").is(keyword));
        long count = mongoTemplate.count(query, ApUserSearch.class);

        //2.根据返回数量判断新增 更新时间
        if (count == 0) {
            ApUserSearch apUserSearch = new ApUserSearch();
            apUserSearch.setKeyword(keyword);
            apUserSearch.setEquipmentId(equipmentId);
            apUserSearch.setUserId(userId);
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        } else {
            Update update = new Update();
            update.set("createdTime", new Date());
            mongoTemplate.updateFirst(query, update, ApUserSearch.class);
        }
        //TODO 保存搜索记录同时 将用户搜索关键词 保存到联想词库中
    }

    /**
     * 获取用户最新前5条搜索记录
     *
     * @param dto 入参条件
     * @return
     */
    @Override
    public ResponseResult load(ApArticleSearchDto dto) {
        //1.封装查询MongoDB条件 用户ID或者设备ID，排序，前5条
        Query query = new Query();
        User user = UserThreadLocalUtil.get();
        if (user != null) {
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        } else {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        PageRequest pageRequest = PageRequest.of(0, 5, Sort.Direction.DESC, "createdTime");
        query.with(pageRequest);
        //2.执行查询返回结果
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(list);
    }

    /**
     * 删除用户操作历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delete(ApArticleSearchDto dto) {
        //1.封装删除条件
        Query query = new Query();
        List<ApUserSearch> hisList = dto.getHisList();
        if (!CollectionUtils.isEmpty(hisList)) {
            List<String> collect = hisList.stream().map(ApUserSearch::getId).collect(Collectors.toList());
            query.addCriteria(Criteria.where("id").in(collect));
            //2.执行删除文档数据
            mongoTemplate.remove(query, ApUserSearch.class);
        }
        return ResponseResult.okResult();
    }
}
